home *** CD-ROM | disk | FTP | other *** search
/ El Mac 9 / El Mac 9.iso / Shareware / Applications / MathPad 2.4 / Examples / root finder < prev    next >
Encoding:
Text File  |  1994-06-14  |  1.2 KB  |  39 lines  |  [TEXT/MPad]

  1. -- Find a root of a function.
  2. -- The user must supply a definition f(x) and x1,x2 values that bracket the root. The root is found to within ±tol (default setting 1e-7).
  3. -- Technically the sign of f(x) should be different at x1 and at x2 (this guarantees there is at least one root between x1 and x2) but this routine will usually converge as long as there is a root somewhere near x1 or x2.
  4.  
  5. -- example
  6.  
  7. f(x) = x^3 - 2*x
  8.  
  9. plot f(X)
  10. Xmin=-2; Xmax=2
  11.  
  12. r1:=root(-2,-1), r1:-1.414
  13. r2:=root(-1,1),  r2:0.000
  14. r3:=root(1,2),   r3:1.414
  15.  
  16. plot {{r1,r2,r3},{0,0,0}}
  17.  
  18. --------------------
  19. -- This routine uses the "false position" algorithm. The next guess is obtained by finding x at the zero crossing of a line drawn between the previous guesses.
  20.  
  21. root(x1,x2) = flo:=f(x1),
  22.    fhi:=f(x2),
  23.    ((xl:=x1,xh:=x2) when flo<fhi,  -- order xl,xh
  24.     (xl:=x2,xh:=x1,swap:=flo,flo:=fhi,fhi:=swap)),
  25.    delta:=tol,  -- so "while" will do 1st loop
  26.    ((tryx:=xl+(xh-xl)*flo/(flo-fhi) when flo≠fhi,
  27.      tryx:=xl+tol*2), -- avoid zero slope
  28.     try:=f(tryx),
  29.     (delta:=xl-tryx,
  30.       xl:=tryx,
  31.       flo:=try) when try<0,
  32.     (delta:=xh-tryx,
  33.       xh:=tryx,
  34.       fhi:=try) ) while abs(delta)≥tol,
  35.    tryx  -- return last guess
  36.  
  37. tol=1e-7
  38.  
  39.